package com.stu.Demo;

import com.stu.entity.Dept;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * chatgpt优化demo4
 * @author zy
 * @date 2025/3/3 15:40
 */
public class JDBCDemo5 {
    private static final String URL = "jdbc:mysql://localhost:3306/empdb?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";

    // 静态代码块加载 JDBC 驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("数据库驱动加载失败", e);
        }
    }

    public static void main(String[] args) {
        Dept dept = new Dept(90, "客户端部门", "苏州");
        Dept dept2 = new Dept(80, "服务端部门", "南京");

        try {
            // int insertRow = insertDept(dept);
            // int deleteRow = deleteDept(dept);
            int updateRow = updateDept(dept2);

            // System.out.println(insertRow);
            // System.out.println(deleteRow);
            System.out.println(updateRow);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 获取数据库连接
    private static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    // 通用的数据库操作方法
    private static int executeUpdate(String sql, Object... params) throws SQLException {
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            return pstmt.executeUpdate();
        }
    }

    // 插入数据
    private static int insertDept(Dept dept) throws SQLException {
        String sql = "INSERT INTO dept VALUES (?, ?, ?)";
        return executeUpdate(sql, dept.getDeptno(), dept.getDname(), dept.getLoc());
    }

    // 删除数据
    private static int deleteDept(Dept dept) throws SQLException {
        String sql = "DELETE FROM dept WHERE deptno = ?";
        return executeUpdate(sql, dept.getDeptno());
    }

    // 更新数据
    private static int updateDept(Dept dept) throws SQLException {
        String sql = "UPDATE dept SET dname = ?, loc = ? WHERE deptno = ?";
        return executeUpdate(sql, dept.getDname(), dept.getLoc(), dept.getDeptno());
    }
}